package org.yzh.scheduler.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.yzh.scheduler.component.auth.AuthenticationFilter;
import org.yzh.scheduler.component.auth.AuthorizationInterceptor;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorizationInterceptor())
                .addPathPatterns("/schedule-job/*", "/job-log/*");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Bean
    public AuthorizationInterceptor authorizationInterceptor() {
        return new AuthorizationInterceptor();//鉴权拦截器
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean(AuthenticationFilter authenticationFilter) {
        FilterRegistrationBean bean = new FilterRegistrationBean(authenticationFilter);
        bean.addUrlPatterns("/schedule-job/*", "/job-log/*");
        bean.setOrder(0);
        return bean;
    }

    @Bean
    public AuthenticationFilter authenticationFilter() {
        return new AuthenticationFilter();//认证过滤器
    }
}